<?php

	namespace core\controller;

	use core\controller\RestUtils;
class RestRequest {
	private $request_vars;
	private $data;
	private $http_accept;
	private $method;

	function __construct() {
		$this->request_vars = array();
		$this->data = '';
		$this->http_accept = (strpos($_SERVER['HTTP_ACCEPT'], 'json')) ? 'json' : 'xml';
		$this->method = 'get';
	}

	public static function processRequest() {
		$var = $_SERVER['REQUEST_METHOD'];
		$request_method = strtolower($var);
		$return_obj = new RestRequest();
		$data = array();

		switch ($request_method) {
		case 'get':
			# code...
			$data = $_GET;
			break;
		case 'post':
			$data = $_POST;
			# code...
			break;
		case 'put':
			# code...
			parse_str(file_get_contents('php://input'), $put_vars);
			$data = $put_vars;
			break;

		}

		$return_obj->setMethod($request_method);

		$return_obj->setRequestVars($data);

		if (isset($data['data'])) {
			# code...
			$return_obj->setData(json_decode($data['data']));
		}
		return $return_obj;
	}

	public function getdata() {
		return $this->data;
	}

	public function setData($data) {
		$this->data = $data;
	}

	public function getMethod() {
		return $this->method;
	}

	public function setMethod($method) {
		$this->method = $method;
	}

	public function getHttpAccent() {
		return $this->http_accept;
	}

	public function getRequestVars() {
		return $this->request_vars;
	}

	public function setRequestVars($request_vars) {
		$this->request_vars = $request_vars;
	}
	//实例化调用RestUtils

	public static function sendResponse($status = 200, $body = '', $content_type = 'text/html')
	{
		//拼接协议头
		$status_header = 'HTTP/1.1'.$status .''.RestUtils::getStatusCodeMessage( $status);
		header( $status_header);
		header( 'Content-type:' . $content_type);
		if (!empty( $body)){
			echo $body;
			exit();
		}else{
			$message = '';
			switch ($status){
				case 401:
					$message = '您无访问权限';
				break;
				case 404:
					$message = '您到url请求' . $_SERVER['REQUEST_URI'] . '找不到，请重试';
				break;
				case 500:
					$message = '服务器错误，无法响应你到请求';
				break;
				case 501:
					$message = '请求方式无效';
				break;
			}
			//开启服务器签名
			$signature = ($_SERVER['SERVER_SIGNATURE'] == '') ? $_SERVER['SERVER_SOFTWARE'].
			'Server at'. $_SERVER['SERVER_NAME'].'Port'.$_SERVER['SERVER_PORT'] : $_SERVER['SERVER_SIGNATURE'];
			//真实环境
			$body = '
			<!DOCTYPE>
				<html>
				<head>
					<meta http-equiv="Content-Type" content="text/html" charset="utf-8">
					<title>'.$status.''.RestUtils::getStatusCodeMessage( $status).'</title>
				</head>
					<body>
						<h1>'.RestUtils::getStatusCodeMessage( $status).'</h1>
						<p>'.$message.'</p>
						<address>'.$signature.'</address>
					</body>
				</html>';
			echo $body;
			exit();
		}
	}


}


















